import pool from '../config/db.js';

class Address {
  static async getAddresses(userId) {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM addresses WHERE user_id = ? ORDER BY created_at DESC',
        [userId]
      );
      return rows;
    } catch (error) {
      console.error('Error in getAddresses:', error);
      throw error;
    }
  }

  static async addAddress(userId, addressData) {
    try {
      const { name, phone, province, city, address, postcode } = addressData;
      const [result] = await pool.query(
        `INSERT INTO addresses 
         (user_id, name, phone, province, city, address, postcode) 
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [userId, name, phone, province, city, address, postcode]
      );
      return result.insertId;
    } catch (error) {
      console.error('Error in addAddress:', error);
      throw error;
    }
  }

  static async updateAddress(userId, addressId, addressData) {
    try {
      const { name, phone, province, city, address, postcode } = addressData;
      const [result] = await pool.query(
        `UPDATE addresses 
         SET name = ?, phone = ?, province = ?, city = ?, 
             address = ?, postcode = ?
         WHERE id = ? AND user_id = ?`,
        [name, phone, province, city, address, postcode, addressId, userId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('Error in updateAddress:', error);
      throw error;
    }
  }

  static async deleteAddress(userId, addressId) {
    try {
      const [result] = await pool.query(
        'DELETE FROM addresses WHERE id = ? AND user_id = ?',
        [addressId, userId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('Error in deleteAddress:', error);
      throw error;
    }
  }
}

export default Address; 